using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using LumenWorks.Framework.IO.Csv;
using StockTrader.FrontEnd.DataContract;
using StockTrader.FrontEnd.MarketViewer.DAL;
using StockTrader.FrontEnd.MarketViewer.Business;
using Microsoft.Office.Interop.Excel;

namespace StockTrader.FrontEnd.MarketViewer
{
    public partial class frmMain : Form
    {

        private delegate void ChangeProgressDlgt(int progressValue);

        public frmMain()
        {
            InitializeComponent();
        }

        private string getDataFile()
        {
            OpenFileDialog dialog = new OpenFileDialog();
            dialog.Filter = "Market file (*.txt)|*.txt";
            dialog.InitialDirectory = "c:\\";
            dialog.Title = "Select data file to import ...";
            return (dialog.ShowDialog() == DialogResult.OK) ? dialog.FileName : null;
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Environment.Exit(1);
        }

        private void btnImport_Click(object sender, EventArgs e)
        {
            DataConvertion frmCnt = new DataConvertion(this);
            frmCnt.Show();
        }


        string[] ConvertToStringArray(System.Array values)
        {

            // create a new string array
            string[] theArray = new string[values.Length];

            // loop through the 2-D System.Array and populate the 1-D String Array
            for (int i = 1; i <= values.Length; i++)
            {
                if (values.GetValue(1, i) == null)
                    theArray[i - 1] = "";
                else
                    theArray[i - 1] = (string)values.GetValue(1, i).ToString();
            }

            string strErrFile = "c:\\ClientError.txt";
            using (FileStream Erfs = new FileStream(strErrFile, FileMode.OpenOrCreate, FileAccess.ReadWrite))
            {
                if (null != Erfs)
                {
                    using (StreamWriter sws = new StreamWriter(Erfs))
                    {
                        foreach (string tx in theArray)
                        {
                            sws.WriteLine(tx);
                        }

                    }
                }
            }


            return theArray;
        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            try
            {
                SetTooltips();
                this.WindowState = FormWindowState.Maximized;
                AutoSuggest();
            }
            catch (Exception ex)
            {
                MessageBox.Show("Không kết nối được với dữ liệu");
            }
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            #region Parm builder
            string symbol = (txtSymbol.Text.Trim().Length > 0) ? txtSymbol.Text.Trim() : null;
            string side = (txtSide.Text.Trim().Length > 0) ?
                           txtSide.Text.Trim().Substring(0, 1) : null;
            string orderType = null;
            string status = null;
            string accountNo = (txtAccountNo.Text.Trim().Length > 0) ? txtAccountNo.Text.Trim() : null; ;
            string oragnization = (txtOrganization.Text.Trim().Length > 0) ?
                                    txtOrganization.Text.Trim().Substring(0, 1) : null;
            string securitiesCompany = (txtSecuritiesCompany.Text.Trim().Length > 0) ?
                                        txtSecuritiesCompany.Text.Trim() : null;
            int fromTime = 0; // (txtFromTime.Text.Trim().Length > 0) ? txtFromTime.Text : null;
            int toTime = 0; // (txtToTime.Text.Trim().Length > 0) ? txtToTime.Text : null;
            int toVol = Convert.ToInt32(txtVolTo.Text.Trim().Length.Equals(0) ? "20000" : txtVolTo.Text.Trim());
            int fromVol = Convert.ToInt32(txtVolFrom.Text.Trim().Length.Equals(0) ? "3000" : txtVolFrom.Text.Trim());
            DateTime fromDate = dtFromDate.Value;
            DateTime toDate = dtToDate.Value;

            int fromMVol = 0;
            int toMVol = 999999999;

            #endregion

            #region Update result
            DALclient dac = new DALclient();
            HoseMarketSummaryUI result = dac.getDailyOrderSummaryWithAccountNo(fromDate, toDate, securitiesCompany, oragnization, side, symbol, 0, 9999999, 0, 99999999, accountNo);

            HoseMarketSummaryUI resultTotal = dac.getDailyOrderSummaryWithAccountNo(fromDate, toDate, null, null, null, symbol, 0, 999999, 0, 9999999, accountNo);


            lkSecuritiesName.Text = dac.getSecuritiesNameBySymbol(txtSymbol.Text).Trim();
            lkCompanyName.Text = (dac.getSecurityCompanyByShortName(txtSecuritiesCompany.Text) == null) ?
                                "" : dac.getSecurityCompanyByShortName(txtSecuritiesCompany.Text).Name;

            //             lblVol.Text = String.Format("{0:N0}", result.Vol);
            //             lblVolPercent.Text = String.Format("{0:N1}",
            //                 Convert.ToDecimal(result.Vol * 1.0 / (resultTotal.Vol.Equals(0) ? 1 : resultTotal.Vol) * 100)) + "%";

            lblMVol.Text = String.Format("{0:N0}", result.Mvol);
            lblMVolPercent.Text = String.Format("{0:N1}",
                Convert.ToDecimal(result.Mvol * 1.0 / (resultTotal.Mvol.Equals(0) ? 1 : resultTotal.Mvol) * 100)) + "%";
            // 
            //             if (!string.IsNullOrEmpty(txtSecuritiesCompany.Text) && (result.Vol > 0))
            //             {
            //                 double ratio = Convert.ToDouble(result.Mvol * 1.0 / (result.Vol.Equals(0) ? 1 : result.Vol)) * 100;
            //                 txtRatio.Text = String.Format("{0:N1}", ratio) + "%";
            //                 if (ratio > 50)
            //                     txtRatio.ForeColor = Color.Green;
            //                 else
            //                     txtRatio.ForeColor = Color.Red;
            //             }
            //             else
            //                 txtRatio.Text = "";
            #endregion

            System.Data.DataTable list = dac.getDailyOrderWithAccountNo(fromDate, toDate, securitiesCompany, oragnization, side, symbol, fromVol, toVol, fromMVol, toMVol, accountNo);
            grvDetail.DataSource = list;
            if (list.Rows.Count > 0)
            {
                grvDetail.Columns["TransDate"].HeaderText = "Ngày";
                grvDetail.Columns["Side"].HeaderText = "Mua/bán";
                grvDetail.Columns["Symbol"].HeaderText = "Mã CK";
                grvDetail.Columns["Price"].DefaultCellStyle.Format = "N0";
                grvDetail.Columns["Price"].HeaderText = "Giá";
                grvDetail.Columns["Vol"].DefaultCellStyle.Format = "N0";
                grvDetail.Columns["Vol"].HeaderText = "Khối lượng";
                grvDetail.Columns["MVol"].DefaultCellStyle.Format = "N0";
                grvDetail.Columns["MVol"].HeaderText = "KL khớp";
                grvDetail.Columns["PC"].HeaderText = "Đối tượng";
                grvDetail.Columns["Company"].HeaderText = "Công ty chứng khoán";
                grvDetail.Columns["Company"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleLeft;
                grvDetail.Columns["AccountNo"].HeaderText = "Số TK";
                grvDetail.Columns["OrderType"].Visible = false;
                grvDetail.Columns["Time"].HeaderText = "Thời gian";
                grvDetail.Columns["Status"].HeaderText = "Trạng thái";
            }
            this.Refresh();
        }

        private void AutoSuggest()
        {
            try
            {
                DALclient dac = new DALclient();
                List<SecuritiesCompanyUI> companies = dac.getSecuritiesCompany();
                AutoCompleteStringCollection companiesUI = new AutoCompleteStringCollection();
                foreach (SecuritiesCompanyUI item in companies)
                    companiesUI.Add(item.ShortName);
                txtSecuritiesCompany.AutoCompleteCustomSource = companiesUI;

                List<string> symbols = dac.getSecuritiesSymbol();
                AutoCompleteStringCollection symbolsUI = new AutoCompleteStringCollection();
                foreach (string item in symbols)
                    symbolsUI.Add(item);
                txtSymbol.AutoCompleteCustomSource = symbolsUI;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Oops!");
            }

        }

        private void SetTooltips()
        {
            ToolTip tt = new ToolTip();
            tt.SetToolTip(txtSymbol, "Mã chứng khoán");
            tt.SetToolTip(txtVolFrom, "MUA hoặc BÁN");
        }

        private void txtSymbol_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue.Equals(13))
            {
                btnRefresh_Click(sender, e);
            }
        }

        private void btnGetSessionData_Click(object sender, EventArgs e)
        {
            SessionData frmSessionData = new SessionData(this);
            frmSessionData.Show();
        }

        private void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                #region Parm builder
                string symbol = (txtSymbol.Text.Trim().Length > 0) ? txtSymbol.Text.Trim() : null;
                string side = (txtSide.Text.Trim().Length > 0) ?
                               txtSide.Text.Trim().Substring(0, 1) : null;
                string orderType = null;
                string status = null;
                string accountNo = null;
                string oragnization = null;
                string securitiesCompany = (txtSecuritiesCompany.Text.Trim().Length > 0) ?
                                            txtSecuritiesCompany.Text.Trim() : null;
                int fromTime = 0; // (txtFromTime.Text.Trim().Length > 0) ? txtFromTime.Text : null;
                int toTime = 0; // (txtToTime.Text.Trim().Length > 0) ? txtToTime.Text : null;
                int toVol = Convert.ToInt32(txtVolTo.Text.Trim().Length.Equals(0) ? "20000" : txtVolTo.Text.Trim());
                int fromVol = Convert.ToInt32(txtVolFrom.Text.Trim().Length.Equals(0) ? "3000" : txtVolFrom.Text.Trim());
                DateTime fromDate = dtFromDate.Value;
                DateTime toDate = dtToDate.Value;
                int fromMVol = 0;
                int toMVol = 999999999;

                #endregion

                int[] Columns = { 0, 2, 3, 5, 7, 8, 10 };
                string[] Headers = { "Ngày", "Mua/bán", "Mã CK", "Giá", "KL", "KL khớp", "Cty" };
                Export ep = new Export("Win");
                DALclient dac = new DALclient();

                SaveFileDialog saveFileDialog1 = new SaveFileDialog();
                saveFileDialog1.Filter = "Excel|*.xls";
                saveFileDialog1.Title = "Save as Excel file";
                saveFileDialog1.ShowDialog();

                if (saveFileDialog1.FileName != "")
                {
                    System.Data.DataTable list = dac.getDailyOrder(fromDate, toDate, securitiesCompany, oragnization, side, symbol, fromVol, toVol, fromMVol, toMVol);
                    ep.ExportDetails(list, Columns, Export.ExportFormat.Excel, saveFileDialog1.FileName);
                    MessageBox.Show("Done");
                }
            }
            catch
            {
                MessageBox.Show("Fail");
            }

        }

    }
}
